﻿using System.IO;
using Json;
using MobilePal.State;

namespace MobilePal.Log
{
    public class JsonLogger : ILogger
    {
        #region Fields

        private readonly string _filename;
        private readonly object _syncRoot = new object();

        #endregion

        #region Constructors/Finalizers

        public JsonLogger(string filename)
        {
            _filename = filename;
        }

        #endregion

        #region Methods

        public void DumpActivity(Activity activity)
        {
            lock (_syncRoot)
            {
                IJsonWrapper jsonData;

                if (File.Exists(_filename))
                {

                    using (var logReader = File.OpenText(_filename))
                    {
                        jsonData = JsonMapper.ToJsonData(logReader);
                    }
                }
                else
                {
                    jsonData = new JsonData();
                    jsonData.SetJsonType(JsonType.Array);
                }

                if (!jsonData.IsArray)
                {
                    throw new JsonException("Invalid log format");
                }

                var activityLogEntry = new ActivityLogEntry(activity);
                var activityData = JsonMapper.ToJsonData(activityLogEntry);

                jsonData.GetList().Add(activityData);

                using (var logWriter = File.CreateText(_filename))
                {
                    var json = JsonMapper.ToJson(jsonData);

                    logWriter.Write(json);
                }                
            }
        }
        #endregion
    }
}
